# 多阶段构建 - 第一阶段：构建前端
FROM node:18-alpine AS frontend-builder

WORKDIR /app/frontend

# 复制前端 package.json 并安装依赖
COPY frontend/package*.json ./
RUN npm install

# 复制前端代码并构建
COPY frontend/ ./
RUN npm run build

# 多阶段构建 - 第二阶段：构建后端依赖
FROM node:18-alpine AS backend-builder

WORKDIR /app/backend

# 复制后端 package.json 并安装生产依赖
COPY backend/package*.json ./
RUN npm install --production

# 多阶段构建 - 第三阶段：最终运行环境
FROM node:18-alpine

# 安装 nginx
RUN apk add --no-cache nginx

# 设置工作目录
WORKDIR /app

# 从构建阶段复制后端代码和依赖
COPY --from=backend-builder /app/backend/node_modules ./backend/node_modules
COPY backend/ ./backend/

# 使用 Docker 环境配置
RUN cp /app/backend/.env.docker /app/backend/.env

# 从构建阶段复制前端构建产物
COPY --from=frontend-builder /app/frontend/build /usr/share/nginx/html

# 创建上传目录
RUN mkdir -p /app/backend/uploads

# 配置 nginx
RUN mkdir -p /run/nginx && \
    echo 'server {' > /etc/nginx/http.d/default.conf && \
    echo '    listen 80;' >> /etc/nginx/http.d/default.conf && \
    echo '    root /usr/share/nginx/html;' >> /etc/nginx/http.d/default.conf && \
    echo '    index index.html;' >> /etc/nginx/http.d/default.conf && \
    echo '    location / {' >> /etc/nginx/http.d/default.conf && \
    echo '        try_files $uri $uri/ /index.html;' >> /etc/nginx/http.d/default.conf && \
    echo '    }' >> /etc/nginx/http.d/default.conf && \
    echo '}' >> /etc/nginx/http.d/default.conf

# 创建启动脚本
RUN echo '#!/bin/sh' > /app/start.sh && \
    echo 'nginx' >> /app/start.sh && \
    echo 'cd /app/backend && node src/server.js' >> /app/start.sh && \
    chmod +x /app/start.sh

# 暴露端口
EXPOSE 3000 80

# 启动应用
CMD ["/app/start.sh"]
